package cn.qy.java.base.ch21;

import java.util.Random;

/**
 * 集合点
 */
public class Ch21_11_AssemblePoint {
	
    static class AssemblePoint {
    	int count;
    	
    	public AssemblePoint(int count) {
			this.count = count;
		}
    	
		public synchronized void await() throws InterruptedException {
			if (count > 0) {
				count--;
				if (count <= 0) {
					notifyAll();
				} else {
					// 使用 while，防止虚假唤醒
					while (count > 0) {
						wait();
					}
				}
			}
		}
    }

    static class MyThread extends Thread {
    	AssemblePoint assemblePoint;
    	
		public MyThread(AssemblePoint assemblePoint) {
			this.assemblePoint = assemblePoint;
		}
		
		@Override
		public void run() {
			try {
				long mills = new Random().nextInt(5000);
				Thread.sleep(mills);
				// 集合
				this.assemblePoint.await();
				System.out.println("lalala is ok " + mills);
				// 集合后执行其他操作
				Thread.sleep(mills);
				System.out.println("lalala over " + mills);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
    }
	
	public static void main(String[] args) throws Exception {
		int size = 5;
		AssemblePoint assemblePoint = new AssemblePoint(size);
		for(int i = 0; i<size; i++) {
			Thread t = new MyThread(assemblePoint);
			t.start();
		}
	}

}
